<?php

namespace app\api\controller\v47;

use app\aliyun\controller\AliyunFilterWord;
use app\aliyun\controller\AliyunFilterWordV2;
use app\api\controller\v2\Auth;
use app\common\cachemodel\chat\HzChatRecordDetails;
use app\common\cachemodel\zl7\Zl7QuestionAiAnswerRecord;
use app\common\cachemodel\zl8\Zl8TarotAiAnswerRecord;
use app\common\cachemodel\ZlTarotRecords;
use app\common\lib\tarot\Tarot;
use app\common\lib\Util;
use app\common\model\Divination;
use app\common\service\ChatParse;
use think\Env;
use think\Log;
use think\response\Json;

class UserDivination extends Auth
{
    /**
     * 塔罗记录添加
     * @return Json
     * @throws \Exception
     */
    public function tarotSave()
    {
        $typeId = input('type_id/d', 0);
        $question = trim(input('question/s', ''));
        $isSelectGuide = input('is_select_guide/d', 0);
        $tarotId = input('tarot_id/d', 0);
        $tarotConfig = config('tarot');
        if (Util::commentCheck($this->user['id'], ['action' => 'tarotSave', 'question' => $question, 'type_id' => $typeId, 'is_select_guide' => $isSelectGuide, 'tarot_id' => $tarotId], 5) && (int)$this->user['id'] != 10834769)
        {//mark 17333657763 手机号的uid为10834769，可以测试并发
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }

        $tarotRecordModel = new ZlTarotRecords();
        if ($tarotId)
        {   // 开始 抽 指引牌
            $tarotInfo = $tarotRecordModel->getInfoById($tarotId);
            if (!$tarotInfo || $this->user['id'] !== (int)$tarotInfo['uid'])
            {
                return show(config('code.error'), '服务异常，记录不存在');
            }
            //  塔罗牌阵 信息
            $tarotTypeInfo = $tarotConfig['tarot_type'][$tarotInfo['tarot_type']];
            $tarotModel = new Tarot();
            $cardList = $tarotModel->getTarotCard($tarotTypeInfo, 1, $tarotInfo['content']);
            if (empty($cardList))
            {
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
            $tarotInfo['content'] = array_merge($tarotInfo['content'], $cardList);

            $list = array_column($tarotInfo['content'], null, 'location');
            ksort($list);
            $list = array_values($list);
            $updateData = [
                'content' => json_encode($list, JSON_UNESCAPED_UNICODE),
                'update_time' => $this->request->time(),
            ];
            $res = $tarotRecordModel->updateData($tarotId, $updateData);
            if ($res)
            {
                $hzChatRecordDetailsModel = new HzChatRecordDetails();
                $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);
                $resData = [
                    'tarot_id' => $tarotId,
                    'type_id' => $tarotInfo['tarot_type'],
                    'tarot_cards' => $tarotModel->getTarotInfo($tarotConfig, $cardList, $tarotInfo['tarot_type'], $numData['res_num']),
                    'num' => $numData['res_num'],
                    'question' => $tarotInfo['question'],   // 问题
                    'title' => $tarotConfig['tarot_type_name'][$tarotInfo['tarot_type']],  // 牌阵名字
                ];
                return show(config('code.success'), '请求成功', $resData);
            } else
            {
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
        } else
        {   // 抽牌
            $isSelectGuide = 1;
            if (!isset($tarotConfig['tarot_type'][$typeId]) || !in_array($isSelectGuide, [0, 1], true) || empty($question))
            {
                return show(config('code.error'), '请求异常，请稍后再试～');
            }
            if (mb_strlen($question) > 30)
            {
                return show(config('code.error'), '提问最多30字');
            }

            $aliRes = AliyunFilterWord::checkText($question);
            if ($aliRes)
            {
                return show(0, '检测到敏感内容');
            }
            //  塔罗牌阵 信息
            $tarotTypeInfo = $tarotConfig['tarot_type'][$typeId];
            $tarotModel = new Tarot();
            $cardList = $tarotModel->getTarotCard($tarotTypeInfo, $isSelectGuide);
            $data = [
                'uid' => $this->user['id'],
                'question' => $question,
                'type' => 3,
                'gid' => 0,
                'status' => 0,
                'tarot_type' => $typeId,
                'content' => json_encode($cardList, JSON_UNESCAPED_UNICODE),
                'create_time' => $this->request->time(),
            ];

            $tarotId = $tarotRecordModel->saveData($this->user['id'], $data);
            if ($tarotId)
            {
                $hzChatRecordDetailsModel = new HzChatRecordDetails();
                $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);
                $aiAnswerNum = $numData['pay_num'] + $numData['admin_num'];
                $resData = [
                    'tarot_id' => $tarotId,
                    'type_id' => $typeId,
                    'tarot_cards' => $tarotModel->getTarotInfo($tarotConfig, $cardList, $typeId, $aiAnswerNum),
                    'num' => $aiAnswerNum,
                    'question' => $question,   // 问题
                    'title' => $tarotConfig['tarot_type_name'][$typeId],  // 牌阵名字
                ];
                $resData['btn_name'] = $resData['tarot_cards'][0]['btn_name'];
                $resData['use_num'] = $tarotModel->getGetTarotTypeUnlockDecNum($typeId);

                return show(config('code.success'), '请求成功', $resData);
            } else
            {
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
        }
    }

    /**
     * 塔罗详情
     */
    public function tarotInfo()
    {
        $tarotId = input('tarot_id/d', 0);

        $tarotRecordModel = new ZlTarotRecords();
        $tarotInfo = $tarotRecordModel->getInfoById($tarotId);
        if (!$tarotInfo || $this->user['id'] !== (int)$tarotInfo['uid'])
        {
            return show(config('code.error'), '服务异常，记录不存在');
        }
        $tarotConfig = config('tarot');
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);
        if (Util::checkAppVersion('2.15.0') !== '小')
        {
            $aiAnswerNum = $numData['res_num'];
        } else
        {
            $aiAnswerNum = $numData['pay_num'] + $numData['admin_num'];
        }
        $tarotModel = new Tarot();
        $resData = [
            'tarot_id' => $tarotId,
            'type_id' => $tarotInfo['tarot_type'],
            'tarot_cards' => $tarotModel->getTarotInfo($tarotConfig, $tarotInfo['content'], $tarotInfo['tarot_type'], $aiAnswerNum),
            'num' => $aiAnswerNum,
            'question' => $tarotInfo['question'],   // 问题
            'title' => $tarotConfig['tarot_type_name'][$tarotInfo['tarot_type']],  // 牌阵名字
        ];
        $resData['btn_name'] = $resData['tarot_cards'][0]['btn_name'];
        $resData['use_num'] = $tarotInfo['status'] === 1 ? 0 : $tarotModel->getGetTarotTypeUnlockDecNum($tarotInfo['tarot_type']);

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取 塔罗 AI解答 记录详情
     * @return Json
     * @throws \Exception
     */
    public function getTarotAiAnswerDetail()
    {
        $tarotId = input('tarot_id/d', 0);
        if (!$tarotId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $tarotRecordModel = new ZlTarotRecords();
        $tarotInfo = $tarotRecordModel->getInfoById($tarotId);
        if (!$tarotInfo || $this->user['id'] !== (int)$tarotInfo['uid'])
        {
            return show(config('code.error'), '服务异常，记录不存在');
        }

        $zl8TarotAiAnswerRecordModel = new Zl8TarotAiAnswerRecord();
        $data = $zl8TarotAiAnswerRecordModel->getListPage($tarotId, 'id', [], 0, 'desc');
        $data['data'] = $zl8TarotAiAnswerRecordModel->dataInit($data['data']);
        if ($data['data'])
        {
            $d = array_column($data['data'], null, 'id');
            ksort($d);
            $data['data'] = array_values($d);
        }
        $dataList = $zl8TarotAiAnswerRecordModel->dataResert($tarotInfo, $data['data']);

        $resData = [
            'official_avatar' => $zl8TarotAiAnswerRecordModel->officialAvatar,
            'question' => $tarotInfo['question'],
            'data_list' => $dataList,
        ];
        $delayUnlockCard = null;
        foreach ($tarotInfo['content'] as $itemData)
        {
            if (!$itemData['status'])
            {
                $delayUnlockCard = $itemData;
                break;
            }
        }
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);
        $delayUnlockCardResData = $zl8TarotAiAnswerRecordModel->delayUnlockData($delayUnlockCard, $tarotInfo['tarot_type'], $numData['res_num']);
        if ($delayUnlockCardResData)
        {
            $resData['data_list'][] = $delayUnlockCardResData;
        }
        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取塔罗占卜历史记录
     */
    public function getTarotList()
    {
        $type = input('type/d', 2);

        if (!in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        if ($type === 2)
        {
            $tarotRecordModel = new ZlTarotRecords();

            $data = $tarotRecordModel->getListPage($this->user['id']);

            $data['data'] = $tarotRecordModel->pageDataReset($data['data'], 2);

            return show(config('code.success'), '请求成功', $data);
        }

        $map['uid'] = $this->user['id'];
        $map['page'] = input('page/d', 1);
        try
        {
            $data = (new Divination())->getListPage($map);
            if ((!isset($data['data']) || empty($data['data'])) && $map['page'] === 1)
            {
                return show(200, '您的提问记录为空，立即去提问吧~', $data);
            }

            $d = [];
            if (isset($data['data']))
            {
                $oss = Env::get('host.photo');
                foreach ($data['data'] as $item)
                {
                    $aiContent = (new Zl7QuestionAiAnswerRecord())->getUserAiInfo($type, $this->user['id'], $item['id'])['content'];
                    $d[] = [
                        'id' => (int)$item['id'],
                        'question' => $item['question'],
                        'planet' => (int)$item['planet'],
                        'sign' => (int)$item['sign'],
                        'house' => (int)$item['house'],
                        'tag' => $aiContent !== null ? $oss . '/test/ai/divination_tarot_ai.png' : '',
                        'create_time' => date('Y.m.d H:i', $item['create_time']),
                    ];
                }
            }
            $data['data'] = $d;
            return show(200, '成功', $data);
        }
        catch (\Exception $e)
        {
            Log::write('获取提问历史记录失败' . $e->getMessage() . var_export(request()->param(), true), 'error', true);

            return show(config('code.error'), '网络错误');
        }
    }

    /**
     * 塔罗 卡牌 AI解锁
     * @return Json
     * @throws \Exception
     */
    public function tarotCardAiUnlock()
    {
        $tarotId = input('tarot_id/d', 0);
        $location = input('location/d', 0);

        if (Util::commentCheck($this->user['id'], ['action' => 'tarotCardAiUnlock', 'location' => $location, 'tarot_id' => $tarotId], 5) && (int)$this->user['id'] != 10834769)
        {//mark 17333657763 手机号的uid为10834769，可以测试并发
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        $tarotRecordModel = new ZlTarotRecords();
        $tarotInfo = $tarotRecordModel->getInfoById($tarotId);
        if (!$tarotInfo || $this->user['id'] !== (int)$tarotInfo['uid'])
        {
            return show(config('code.error'), '服务异常，记录不存在');
        }
        $resCardList = [];
        // if ($tarotInfo['tarot_type'] === 2001)
        // {   // 时间之剑 牌阵 解锁  一次性全部解锁
        if ($tarotInfo['status'] === 1)
        {
            return show(config('code.error'), '服务异常，已经解锁过了');
        }

        $aliRes = AliyunFilterWordV2::checkAIText($tarotInfo['question']);
        if ($aliRes['status'] === false)
        {
            return show(0, '检测到敏感内容');
        }

        $location = -1;
        foreach ($tarotInfo['content'] as $k => $item)
        {
            $tarotInfo['content'][$k]['status'] = 1;
            $resCardList[] = $tarotInfo['content'][$k];
        }
        // } else
        // {   // 其他牌阵 解锁
        //     foreach ($tarotInfo['content'] as $k => $item)
        //     {
        //         if ($item['location'] === $location)
        //         {
        //             $tarotInfo['content'][$k]['status'] = 1;
        //             $resCardList[] = $tarotInfo['content'][$k];
        //         }
        //     }
        // }
        if (empty($resCardList))
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $decNum = (new Tarot())->getGetTarotTypeUnlockDecNum($tarotInfo['tarot_type']);
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);
        if (Util::checkAppVersion('2.15.0') !== '小')
        {
            if ($numData['res_num'] < $decNum)
            {   // 会话次数 用尽
                return show(config('code.error'), 'AI解答次数不足，解读失败～');
            }
            // 扣除次数
            $numData = $hzChatRecordDetailsModel->chatQueryEndNumDec($this->user['id'], $numData, $decNum);
            $aiAnswerNum = $numData['res_num'];
        } else
        {
            $aiAnswerNum = $numData['pay_num'] + $numData['admin_num'];
            if ($aiAnswerNum < $decNum)
            {   // 会话次数 用尽
                return show(config('code.error'), 'AI解答次数不足，解读失败～');
            }
            // 扣除次数
            $numData = $hzChatRecordDetailsModel->chatQueryEndNumDec($this->user['id'], $numData, $decNum, false);
            $aiAnswerNum = $numData['pay_num'] + $numData['admin_num'];
        }
        $insertData = [
            'uid' => $this->user['id'],
            'tarot_id' => $tarotId,
            'status' => 0,
            'location' => $location,
            'num_type' => $numData['use_type'],
            'content' => '',
            'create_time' => $this->request->time(),
        ];
        $zl8TarotAiAnswerRecordModel = new Zl8TarotAiAnswerRecord();
        $resId = $zl8TarotAiAnswerRecordModel->SaveData($insertData);
        $insertData['id'] = $resId;
        $updateData = [
            'content' => json_encode($tarotInfo['content'], JSON_UNESCAPED_UNICODE),
        ];
        if (!$tarotInfo['status'])
        {
            $updateData['status'] = 1;
        }
        $tarotRecordModel->updateData($tarotId, $updateData);

        $resData = $zl8TarotAiAnswerRecordModel->dataResert($tarotInfo, [$insertData]);
        $resData = current($resData);
        $resData['official_avatar'] = $zl8TarotAiAnswerRecordModel->officialAvatar;
        $resData['num'] = $aiAnswerNum;
        // $delayUnlockCard = null;
        // foreach ($tarotInfo['content'] as $itemData)
        // {
        //     if (!$itemData['status'])
        //     {
        //         $delayUnlockCard = $itemData;
        //         break;
        //     }
        // }
        // $resData['next_unlock_card'] = $zl8TarotAiAnswerRecordModel->delayUnlockData($delayUnlockCard, $tarotInfo['tarot_type'], $numData['res_num']);
        $resData['next_unlock_card'] = null;

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * @return void
     */
    public function getTarotCardAiAnswerStream()
    {
        $tarotId = input('tarot_id/d', 0);
        $id = input('id/d', 0);
        if (Util::commentCheck($this->user['id'], ['action' => 'getTarotCardAiAnswerStream', 'id' => $id, 'tarot_id' => $tarotId], 5) && (int)$this->user['id'] != 10834769)
        {//mark 17333657763 手机号的uid为10834769，可以测试并发
            echo '操作频繁，请刷新页面后再次尝试～';
            return;
        }
        $tarotRecordModel = new ZlTarotRecords();
        $tarotInfo = $tarotRecordModel->getInfoById($tarotId);
        if (!$tarotInfo || $this->user['id'] !== $tarotInfo['uid'])
        {
            echo '服务异常，数据不存在';
            return;
        }
        $zl8TarotAiAnswerRecordModel = new Zl8TarotAiAnswerRecord();
        $aiAnswerInfo = $zl8TarotAiAnswerRecordModel->getInfoById($id);
        if (!$aiAnswerInfo || $this->user['id'] !== $aiAnswerInfo['uid'])
        {
            echo '服务异常，数据不存在';
            return;
        }
        if ($aiAnswerInfo['status'] === 2)
        {
            echo $aiAnswerInfo['content'];
            return;
        }
        $tarotConfig = config('tarot');
        $zl8TarotAiAnswerRecordModel->UpdateData($id, ['status' => 1]);
        //  1=>塔罗-时间之箭
        //  2=>塔罗-恋爱圣三角
        //  3=>塔罗-吉普赛十字牌阵
        //  4=>塔罗-万能牌阵
        //  5=>塔罗-每周运势牌阵
        //  6=>塔罗-身心灵牌阵
        //  7=>塔罗-四元素牌阵
        //  8=>塔罗-六芒星牌阵
        //  9=>塔罗-圣三角
        //  10=>塔罗-灵感对应牌阵
        //  11=>塔罗-抉择牌阵（2选1）
        //  12=>塔罗-抉择牌阵（3选1）
        $typeConfig = [
            1001 => 2,  // '恋爱圣三角',
            1002 => 3,  // '吉普赛十字牌阵',
            2001 => 1,  // '时间之剑',
            2002 => 4,  // '万能牌阵',
            3001 => 5,  // '每周运势牌阵',
            4001 => 6,  // '身心灵牌阵',
            4002 => 7,  // '四元素牌阵',
            4003 => 8,  // '六芒星牌阵',
            4004 => 9,  // '圣三角',
            5001 => 10, // '灵感对应牌阵',
            6001 => 11, // '抉择牌阵（2选1）',
            6002 => 12, // '抉择牌阵（3选1）',
        ];
        $diceOrTarotInfo = [];
        foreach ($tarotInfo['content'] as $cardItem)
        {
            $diceOrTarotInfo[] = $tarotConfig['card_list'][$cardItem['card_id']]['name'] . '.' . ((int)$cardItem['direction'] === 1 ? '正位' : '逆位');
        }

        if (count($diceOrTarotInfo) < count($tarotConfig['tarot_type'][$tarotInfo['tarot_type']]))
        {
            $diceOrTarotInfo[] = '';
        }

        $data = [
            'uid' => $this->user['id'],
            'dice_or_tarot_info' => $diceOrTarotInfo,
            'did' => $tarotId,    // 记录ID
            'type' => $typeConfig[$tarotInfo['tarot_type']],   // 牌阵类型  0=>骰子  1=>塔罗-时间之箭  2=>塔罗-恋爱圣三角  3=>塔罗-吉普赛十字牌阵  4=>塔罗-万能牌阵  5=>塔罗-每周运势牌阵  6=>塔罗-身心灵牌阵  7=>塔罗-四元素牌阵  8=>塔罗-六芒星牌阵  9=>塔罗-圣三角  10=>塔罗-灵感对应牌阵  11=>塔罗-抉择牌阵（2选1）  12=>塔罗-抉择牌阵（3选1）
            'query' => $tarotInfo['question'],  // 问题
            'brand_index' => 0,    // 牌位
            // 'brand_index' => $aiAnswerInfo['location'] === -1 ? 0 : $aiAnswerInfo['location'],    // 牌位
        ];

        $centent = ChatParse::getTarotAiAnswerStreamData($data);
        // 0=>待解答 1=>解答中 2=>解答完成
        if (trim($centent))
        {
            $uData = ['content' => $centent, 'status' => 2];
            if (strpos($centent, 'θ') !== false)
            {
                $uData['content'] = '准准认为你的问题包含敏感信息，换个问题再试试吧。本次解答不扣次数！';
                $uData['num_type'] = 0;
                $incNum = (new Tarot())->getGetTarotTypeUnlockDecNum($tarotInfo['tarot_type']);
                // 返回 AI解答次数
                (new HzChatRecordDetails())->chatQueryEndNumInc($this->user['id'], $aiAnswerInfo['num_type'], $incNum);
            }

            $zl8TarotAiAnswerRecordModel->UpdateData($id, $uData);
        }
    }
}
